layui.use(['form', 'jquery', 'layer', 'laypage', 'flow', 'table'], function() {
	var form = layui.form;
	var $ = layui.$;
	var layer = layui.layer;
	var laypage = layui.laypage;
	var flow = layui.flow;
	var table = layui.table;
	var wait_where = {
			shopping_id: -1,
			page: 1,
			limit: 100
		},
		cart_id_arr = [],
		select_where = {
			cart_id: [],
			page: 1,
			limit: 100
		};
	var format_num = function(s, n) {
		n = n > 0 && n <= 20 ? n : 2;
		s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
		var l = s.split(".")[0].split("").reverse(),
			r = s.split(".")[1];
		t = "";
		for (i = 0; i < l.length; i++) {
			t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
		}
		return t.split("").reverse().join("") + "." + r;
	};
	var calc_money = function(data) {
		var all_money = 0;
		for (var i in data) {
			all_money = all_money + parseFloat(data[i].all_price);
		}
		$('.all_price').html(format_num(all_money, 2, 0));
	}
	var deff_money = function(data) {
		var all_money = parseFloat($('.all_price').html());
		all_money = all_money - parseFloat(data.all_price);
		$('.all_price').html(format_num(all_money, 2, 0));
	}
	var member_id;
	// 初始化未选择table
	table.render({
		elem: '#wait_list',
		id: 'wait_list',
		url: ajax_wait_cart_url,
		method: 'post',
		height: 'full-217',
		where: wait_where,
		cols: [wait_cols],
		page: false,
		toolbar: '#waitToolbar',
		defaultToolbar: []
	});
	// 初始化一选择table
	table.render({
		elem: '#select_list',
		id: 'select_list',
		url: ajax_wait_cart_url,
		method: 'post',
		height: 'full-217',
		where: select_where,
		cols: [select_cols],
		done: function(e) {
			calc_money(e.data);
		},
		page: false,
		toolbar: '#selectToolbar',
		defaultToolbar: []
	});
	var get_member_shopping = function(member_id, shopping_id) {
		var post_where = {
			member_id: member_id,
			limit: 50
		};
		send_info(ajax_customer_url, post_where, function(data) {
			$('.member-shopping-list').html('');
			for (var i in data.data) {
				$('.member-shopping-list').append(create_html(data.data[i], 'layui-col-md3 layui-col-lg2'));
			}
			$('.member-shopping-list').find('li[data-shopping_id="' + shopping_id + '"] .layui-card').trigger('click');
		})
	};
	// 关闭页面
	$('#close_page').on('click', function() {
		parent.layer.closeAll('iframe');
	})
	// 设置布局
	$('.set-left').on('click', function() {
		if ($('.left-box').hasClass('layui-col-md6')) {
			// 右移
			$('.left-box').removeClass('layui-col-md6').addClass('layui-col-md10');
			$('.right-box').removeClass('layui-col-md6').addClass('layui-col-md2');
			$('.view-right-box').hide();
			$('.view-left-box').show();
			table.resize('wait_list');
			table.resize('select_list');
		} else if (!$('.left-box').hasClass('layui-col-md10')) {
			// 左移
			$('.left-box').removeClass('layui-col-md2').addClass('layui-col-md6');
			$('.right-box').removeClass('layui-col-md10').addClass('layui-col-md6');
			$('.view-right-box').show();
			$('.view-left-box').show();
			table.resize('wait_list');
			table.resize('select_list');
		} else {
			return false;
		}
	})
	$('.set-right').on('click', function() {
		if ($('.right-box').hasClass('layui-col-md6')) {
			// 左移
			$('.right-box').removeClass('layui-col-md6').addClass('layui-col-md10');
			$('.left-box').removeClass('layui-col-md6').addClass('layui-col-md2');
			$('.view-left-box').hide();
			table.resize('wait_list');
			table.resize('select_list');
		} else if (!$('.right-box').hasClass('layui-col-md10')) {
			// 右移
			$('.right-box').removeClass('layui-col-md2').addClass('layui-col-md6');
			$('.left-box').removeClass('layui-col-md10').addClass('layui-col-md6');
			$('.view-right-box').show();
			$('.view-left-box').show();
			table.resize('wait_list');
			table.resize('select_list');
		} else {
			return false;
		}
	})
	//布局完成
	$('.view-info-box').on('mouseover', 'li .layui-card', function() {
		$(this).addClass('on');
	}).on('mouseleave', 'li .layui-card', function() {
		$(this).removeClass('on');
	}).on('click', 'li .layui-card', function() {
		$('.view-info-box .layui-card').removeClass('active');
		$('.same-costom').addClass('on');
		$('.invoice-box').show();
		$(this).addClass('active');
		member_id = $(this).parents('li').attr('data-member_id');
		var shopping_id = $(this).parents('li').attr('data-shopping_id');
		get_member_shopping(member_id, shopping_id);
		cart_id_arr = [];
		select_where.cart_id = cart_id_arr.join(',');
		table.reload('select_list', {
			where: select_where
		});
	})

	$('.member-shopping-list').on('mouseover', 'li .layui-card', function() {
		$(this).addClass('on');
	}).on('mouseleave', 'li .layui-card', function() {
		$(this).removeClass('on');
	}).on('click', 'li .layui-card', function() {
		$('.member-shopping-list .layui-card').removeClass('active');
		$(this).addClass('active');
		var member_id = $(this).parents('li').attr('data-member_id'),
			shopping_id = $(this).parents('li').attr('data-shopping_id');
		wait_where.shopping_id = shopping_id;
		wait_where.no_cart_id = cart_id_arr.join(',');
		table.reload('wait_list', {
			where: wait_where
		});
	})
	// 监听表头 选择
	table.on('toolbar(wait_list)', function(obj) {
		switch (obj.event) {
			case 'selectInvoice':
				var checkStatus = table.checkStatus('wait_list');
				var tr = checkStatus.tr;
				if (checkStatus.data.length == 0) {
					layer.msg('请先选择商品', {
						icon: 2,
						anim: 6
					});
					return false;
				}
				checkStatus.data.map(function(obj, i) {
					cart_id_arr.push(obj.cart_id);
				});
				select_where.cart_id = cart_id_arr.join(',');
				table.reload('select_list', {
					where: select_where,
					done: function(e) {
						calc_money(e.data);
					}
				});
				wait_where.no_cart_id = cart_id_arr.join(',');
				table.reload('wait_list', {
					where: wait_where
				});
				break;
			default:
				break;
		}
		return false;
	})
	// 监听表头 移除
	table.on('toolbar(select_list)', function(obj) {
		switch (obj.event) {
			case 'removeInvoice':
				var checkStatus = table.checkStatus('select_list');
				var tr = checkStatus.tr;
				if (checkStatus.data.length == 0) {
					layer.msg('请先选择商品', {
						icon: 2,
						anim: 6
					});
					return false;
				}
				var new_arr = [];
				checkStatus.data.map(function(obj, i) {
					new_arr.push(obj.cart_id);
				});
				console.info(new_arr);
				Array.prototype.diff = function(a) {
					return this.filter(function(i) {
						return a.indexOf(i) < 0;
					});
				}
				cart_id_arr = cart_id_arr.diff(new_arr);
				select_where.cart_id = cart_id_arr.join(',');
				table.reload('select_list', {
					where: select_where,
					done: function(e) {
						calc_money(e.data);
					}
				});
				wait_where.no_cart_id = cart_id_arr.join(',');
				table.reload('wait_list', {
					where: wait_where
				});
				break;
			default:
				break;
		}
		return false;
	})
	// 监听未选择事件
	table.on('tool(wait_list)', function(obj) {
		var data = obj.data;
		var e = obj.event;
		var tr = obj.tr;
		var cart_id = data.cart_id;
		switch (e) {
			case 'select':
				cart_id_arr.push(cart_id);
				select_where.cart_id = cart_id_arr.join(',');
				table.reload('select_list', {
					where: select_where,
					done: function(e) {
						calc_money(e.data);
					}
				});
				obj.del();
				break;
			default:
				break;
		}
	})
	// 监听一选择事件
	table.on('tool(select_list)', function(obj) {
		var data = obj.data;
		var e = obj.event;
		var tr = obj.tr;
		var cart_id = data.cart_id;
		switch (e) {
			case 'remove':
				var new_arr = [];
				for (var i in cart_id_arr) {
					if (cart_id_arr[i] != cart_id) {
						new_arr.push(cart_id_arr[i]);
					}
				}
				cart_id_arr = new_arr;
				wait_where.no_cart_id = cart_id_arr.join(',');
				table.reload('wait_list', {
					where: wait_where
				});
				deff_money(data);
				obj.del();
				break;
			default:
				break;
		}
	})
	var create_html = function(data, md) {
		//console.info(data);
		var html = '<li class="' + md + '" data-shopping_id="' + data.shopping_id +
			'" data-member_id="' + data.member_id + '">' +
			'	<div class="layui-card">' +
			'		<div class="layui-card-body">' +
			'<div class="right-add"><span class="layui-icon layui-icon-ok"></span></div>' +
			'			<img src="' + data.member_info.head_pic_url + '" />' +
			'			<div class="right-box">' +
			'				<div class="layui-ellipsis">' + data.contacts + '</div>' +
			'				<div>' + data.phone + '</div>' +
			'			</div>' +
			'		</div>' +
			'	</div>' +
			'</li>';
		return html;
	}
	var post_where = {
		limit: 10
	};
	var option = {
		elem: '.view-info-box',
		end: ' ',
		scrollElem: '.view-info-box',
		isAuto: true,
		done: function(page, next) {
			var lis = [];
			post_where.page = page;
			$.ajax({
				type: "post",
				url: ajax_customer_url,
				async: true,
				data: post_where,
				dataType: 'json',
				success: function(data) {
					for (var i in data.data) {
						lis.push(create_html(data.data[i], 'layui-col-md12'));
					}
					next(lis.join(''), page < data.count);
				},
				error: function(xhr, type, errorThrown) {
					layer.msg('请求失败，访问地址：' + string_uri, {
						icon: 2,
						anim: 6
					});
					layer.closeAll('loading');
				}
			});
		}
	}
	flow.load(option);
	// 表单input 查询
	$('form[lay-filter="customer_search_form"]').on('input propertychange', 'input[type="text"]', function() {
		if ($(this).prop('comStart')) return;
		var value = $(this).val();
		var name = $(this).attr('name');
		post_where[name] = value;
		$('.view-info-box').html('');
		flow.load(option);
	}).on('compositionstart', 'input[type="text"]', function() {
		$(this).prop('comStart', true);
	}).on('compositionend', 'input[type="text"]', function() {
		$(this).prop('comStart', false);
		$(this).trigger('input');
	});
	// 订单号查询
	$('input[name="order_no"]').on('input propertychange', '', function() {
		if ($(this).prop('comStart')) return;
		var value = $(this).val();
		wait_where.select_order_no = value;
		table.reload('wait_list', {
			where: wait_where
		});
	}).on('compositionstart', function() {
		$(this).prop('comStart', true);
	}).on('compositionend', function() {
		$(this).prop('comStart', false);
		$(this).trigger('input');
	});
	// 申请开票按钮
	$('.apply-btn').on('click', function() {
		if (cart_id_arr.length == 0) {
			layer.msg('请先选择开票商品', {
				icon: 2,
				anim: 6
			})
			return false;
		}
		var order_no_arr = [];
		table.reload('select_list',{
			done:function(res, curr, count){
				//console.info(res);
				for(var i in res.data){
					order_no_arr.push(res.data[i].order_no);
				}
				$('input[name="order_nos"]').val(order_no_arr.join(','));
				console.info(order_no_arr);
			}
		})
		// 获取该用户最后一次开票信息
		var post_json = {
			member_id:member_id,
			no_need_invoice_handle:'yes'
		};
		send_info(ajax_invoice_find_url,post_json,function(data){
			form.val('tpl_add_invoice_info',data.data);
			// 处理例外
			$('input[name="builder_type"][value="'+data.data.builder_type+'"]').prop('checked',true);
			$('input[name="invoice_type"][value="'+data.data.invoice_type+'"]').prop('checked',true);
			if (data.data.invoice_type == 1) {
				$('.invoice_type3').hide();
				$('.invoice_type3 input').attr('lay-verify','');
			} else {
				$('.invoice_type3').show();
				$('.invoice_type3 input').attr('lay-verify','required');
			}
			form.render();
			$('input[name="invoice_money"]').val($('.all_price').html());
			$('input[name="member_id"]').val(member_id);
			layer.open({
				content: $('#invoice_info'),
				type: 1,
				anim: 2,
				title: '开票信息',
				closeBtn: true,
				shadeClose: true,
				area: ['650px', '650px'],
				shade: 0.1
			})
		})
		
	})
	form.on('radio(invoice_type)', function(data) {
		if (data.value == 3) {
			$('.invoice_type3').show(300);
			$('.invoice_type3 input').attr('lay-verify','required');
		} else {
			$('.invoice_type3').hide(300);
			$('.invoice_type3 input').attr('lay-verify','');
		}
	})      
	form.on('submit(submit_invoice)', function(data) {
		var field = data.field;
		field.cart_ids = cart_id_arr.join(',');
		field.invoice_money = field.invoice_money*100;
		field.apply_state = 1;
		field.set_draw_admin = 'yes';
		field.is_invoice = 3;
		var url = $('form[lay-filter="tpl_add_invoice_info"]').attr('action');
		layer.confirm('确认要申请开具发票吗？', {
			icon: 3,
			title: '申请开票'
		}, function(index) {
			send_info(url, field, function(data) {
				location.reload();
				parent.layui.table.reload('invoice_list');
				parent.layer.msg('申请开票成功', {
					icon: 1,
					anim: 6
				});
			})
		})
	})

})
